package com.clouddot.baipai.ui.fragment.V_MainFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.getArcticById.getArcticByIdResponse;
import com.clouddot.baipai.model.beam.getArcticList.ariticInfo;
import com.clouddot.baipai.model.beam.getArcticList.getArcticListResponse;
import com.clouddot.baipai.model.beam.getClassHonorById.getClassHonorByIdResponse;
import com.clouddot.baipai.model.beam.getClassHonorById.honorInfo;
import com.clouddot.baipai.model.beam.getClassInfoById.getClassInfoByIdResponse;
import com.clouddot.baipai.model.beam.getClassInfoList.classInfoItem;
import com.clouddot.baipai.model.beam.getClassInfoList.getClassInfoListResponse;
import com.clouddot.baipai.model.beam.getCurrentCourse.getCurrentCourseResponse;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.adapter.V_Adapter.MyPagerAdapter;
import com.clouddot.baipai.ui.adapter.V_Adapter.V_ClasshonorRecyclerAdapter;
import com.clouddot.baipai.ui.adapter.V_Adapter.V_NewsRecyclerAdapter;
import com.clouddot.baipai.ui.dialog.V_Dialog.V_ContentDailog;
import com.clouddot.baipai.ui.util.recycleView.DivierItemLinear;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static com.clouddot.baipai.ui.activity.H_SMainActivity.MSG_ONE;

/**
 * Created by wxy on 2018/4/10.
 */

public class V_HomeFragment extends BaseFragment implements ViewPager.OnPageChangeListener,View.OnTouchListener{

    private View view;
    private Context context;
    private RelativeLayout noice,teaching,classHonor,schoolNews,classImage;
    private TextView title,time,content;
    private TextView courseName,teacherName,currentTime;
    private ImageView image;
    private ScrollView noiceContent;
    private RecyclerView newsContent,classHonorContent;
    private LinearLayout teachingContent;
    private ImageView left,right;
    private ViewPager viewPager;
    private LinearLayout mBottomLiner;
    private  ImageView[] mBottomImages;

    private V_NewsRecyclerAdapter recyclerAdapter;
    private V_ClasshonorRecyclerAdapter recyclerAdapter1;
    private MyPagerAdapter myPagerAdapter;

    private List<ariticInfo> list   = new ArrayList<>();
    private List<classInfoItem> lists = new ArrayList<classInfoItem>();
    private List<honorInfo> list3 = new ArrayList<honorInfo>();
    private List<ImageView> mItems ;

    private int count = 0;
    private int currentViewPagerItem = -1;
    private boolean isAutoPlay = true;
    private Thread mthread;
    private Thread thread4Data;
    private boolean isFragment;

    private getCurrentCourseThread getCurrentCourseThread;
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getCurrentCourseThread = new getCurrentCourseThread();
        getCurrentCourseThread.start();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();
        view = LayoutInflater.from(context).inflate(R.layout.v_f_homefg,null);
    }

    @Override
    protected void initControls() {
        super.initControls();
        noice = view.findViewById(R.id.classTip);
        teaching = view.findViewById(R.id.teaching);
        schoolNews = view.findViewById(R.id.schoolNews);
        classHonor = view.findViewById(R.id.classsHonor);
        classImage = view.findViewById(R.id.classImage);
        noiceContent = view.findViewById(R.id.noiceContent);
        classHonorContent = view.findViewById(R.id.classHonorContent);
        newsContent = view.findViewById(R.id.newsContent);
        teachingContent = view.findViewById(R.id.teachingContent);

        newsContent.setLayoutManager(new LinearLayoutManager(context));
        newsContent.addItemDecoration(new DivierItemLinear(context,DivierItemLinear.VERTICAL_LIST));
        newsContent.setItemAnimator(new DefaultItemAnimator());
        recyclerAdapter = new V_NewsRecyclerAdapter(context,list);
        newsContent.setAdapter(recyclerAdapter);

        classHonorContent.setLayoutManager(new LinearLayoutManager(context));
        classHonorContent.setItemAnimator(new DefaultItemAnimator());
        recyclerAdapter1 = new V_ClasshonorRecyclerAdapter(context,list3);
        classHonorContent.setAdapter(recyclerAdapter1);

        title = view.findViewById(R.id.title);
        time = view.findViewById(R.id.time);
        content = view.findViewById(R.id.content);

        courseName = view.findViewById(R.id.courseName);
        teacherName = view.findViewById(R.id.teacherName);
        currentTime = view.findViewById(R.id.currentTime);
        image = view.findViewById(R.id.image);

        left = view.findViewById(R.id.left);
        right = view.findViewById(R.id.right);

        viewPager = view.findViewById(R.id.live_view_pager);
        mBottomLiner = view.findViewById(R.id.live_indicator);


        startAnim();

    }


    @SuppressLint("ClickableViewAccessibility")

    @Override
    protected void setListener() {
        super.setListener();
        left.setOnClickListener(leftListener);
        right.setOnClickListener(rightListener);
        viewPager.setOnTouchListener(this);
        viewPager.setOnPageChangeListener(this);
    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onResume() {
        super.onResume();

        if(Env.getAppContext().isInitial) {
            runThreadAction("XXXW");
            runThreadAction("notice");
            runThreadAction("honor");
            runThreadAction("image");
            runThreadAction("getCurrentCourse");
            courseName.setText("正在查询课程...");
            content.setText("正在加载学校通知...");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isFragment = true;
        if(getCurrentCourseThread != null) getCurrentCourseThread.stopRun();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if (actionName.equals("XXXW")) {
            return Env.getAppPresenter().getArcticList(actionName,1,7);
        }else if(actionName.equals("notice") || actionName.equals("image")){
            return Env.getAppPresenter().getClassInfoList(actionName,1, 10);
        }else if(actionName.matches("getNoticeInfo")){
            return Env.getAppPresenter().getClassInfoById(lists.get(count).getId());
        }else if(actionName.equals("getCurrentCourse")){
            return Env.getAppPresenter().getCurrentCourse(Env.getAppContext().classId);
        }else if(actionName.equals("honor")) {
            return Env.getAppPresenter().getClassHonorByIdList(Env.getAppContext().classId, 1,5);
        }else if(actionName.matches("[0-9]+")){
            return Env.getAppPresenter().getArcticById(actionName);
        }else if(actionName.equals("image")){
            return Env.getAppPresenter().getClassInfoList(actionName,1, 1);
        }
        return null;

    }

    private V_ContentDailog dailog;
    private ImageView close;
    private boolean flag = false;
    private List<TextView> TextViews;
    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if(actionName.equals("XXXW")){
            getArcticListResponse response = (getArcticListResponse) result;
            if (response.isSuccess()) {
                flag = true;
                list.clear();
                if(!response.list.isEmpty()){
                    list = response.list;
                }else {
                    list = new ArrayList<>();
                    ariticInfo infoItem = new ariticInfo();
                    infoItem.setTitle("当前没有数据");
                    infoItem.setCreateTime("");
                    list.add(infoItem);
                }

            } else {
                flag = false;
                list = new ArrayList<>();
                ariticInfo infoItem = new ariticInfo();
                infoItem.setTitle(response.getErrMsg());
                infoItem.setCreateTime("");
                list.add(infoItem);
                ToastUtil.showToast(context,response.getErrMsg());
            }
            recyclerAdapter = new V_NewsRecyclerAdapter(context, list);
            newsContent.setAdapter(recyclerAdapter);
            recyclerAdapter.setbtnOnclicker(new V_NewsRecyclerAdapter.btnOnclicker() {
                @Override
                public void onClicked(int position) {
                    if(!flag) return;
                    runThreadAction(list.get(position).getId());
                }
            });
        }else  if(actionName.equals("notice")){
            getClassInfoListResponse response = (getClassInfoListResponse) result;
            if(response.isSuccess()){
                lists = response.list;
                if(!lists.isEmpty()) {
                    runThreadAction("getNoticeInfo");
                }else{
                    content.setText("没有数据");
                }
            }else{
                content.setText(response.getErrMsg());
                ToastUtil.showToast(context,response.getErrMsg());
            }
        }else if(actionName.matches("[0-9]+")) {
            getArcticByIdResponse response = (getArcticByIdResponse) result;
            if(dailog != null) dailog.closeDialog();
            dailog = new V_ContentDailog(context);
            TextViews = dailog.getTextViews();
            TextViews.get(0).setText(response.BaseData.getTitle());
            TextViews.get(1).setText("发布时间："+response.BaseData.getCreateTimeText());
            final String html = EscapeUnescapeUtil.unescape(response.BaseData.getDetail());
            ThreadPool.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    sp =  Html.fromHtml(html, new Html.ImageGetter() {
                        @Override
                        public Drawable getDrawable(String source) {
                            String s =  source.contains("http") ? source:Env.getAppContext().IP + source;
                            InputStream is = null;
                            try {
                                is = (InputStream) new URL(s).getContent();
                                Drawable d = Drawable.createFromStream(is,null);
                                d.setBounds(0, 0, d.getIntrinsicWidth(),
                                        d.getIntrinsicHeight());
                                is.close();
                                return d;
                            } catch (Exception e) {
                                e.printStackTrace();
                                return null;
                            }
                        }
                    }, null);

                    mhandler.sendEmptyMessage(4);
                }
            });

            close = dailog.getCloseView();
            close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dailog.closeDialog();
                }
            });
            dailog.showDialog();
        }else if(actionName.equals("getCurrentCourse")) {
            isFragment = false;
            getCurrentCourseResponse response = (getCurrentCourseResponse) result;
            if(response.isSuccess()){
                teacherName.setText(response.TeacherName);
                currentTime.setText("第"+response.WeekNo+"周"+"第"+response.ClassNo+"节");
                courseName.setText("正在上课： "+response.CourseName);
                Glide.with(context).load(Env.getAppContext().IP+"hh").error(R.drawable.img_02).into(image);

            }else{
                if(Env.getAppContext().classId != null){
                    courseName.setText("该时间段无课程");
                }else{
                    courseName.setText(response.getErrMsg());
                }
            }

        }else if(actionName.equals("image")){
            getClassInfoListResponse response = (getClassInfoListResponse) result;
            if(response.isSuccess()){
                if(!response.list.isEmpty()) {
                    //写在获取图片那里
                    myPagerAdapter = new MyPagerAdapter(addImageView(response.list.get(0).getStrings()), context);
                    viewPager.setAdapter(myPagerAdapter);
                    if(response.list.get(0).getStrings().size() > 1) startAutoPlay();
                    creatCriclePoint();
                }else{
                    ToastUtil.showToast(context,"班级暂时没有图片");
                }
            }else{
                ToastUtil.showToast(context,response.getErrMsg());

            }
        }else if(actionName.equals("honor")) {
            getClassHonorByIdResponse response = (getClassHonorByIdResponse) result;
            if (response.isSuccess()) {

                if (!response.list.isEmpty()) {
                    list3 = response.list;
                } else {
                    list3 = new ArrayList<>();
                    honorInfo infoItem = new honorInfo();
                    infoItem.setHonorItemText("当前没有班级荣誉");
                    infoItem.setEventDate("");
                    infoItem.setHonorLevelText("");
                    list3.add(infoItem);
                }

            } else {
                list3 = new ArrayList<>();
                honorInfo infoItem = new honorInfo();
                infoItem.setHonorItemText(response.getErrMsg());
                infoItem.setEventDate("");
                infoItem.setHonorLevelText("");
                list3.add(infoItem);
                ToastUtil.showToast(context, response.getErrMsg());
            }
            recyclerAdapter1 = new V_ClasshonorRecyclerAdapter(context, list3);
            classHonorContent.setAdapter(recyclerAdapter1);
        }else if(actionName.equals("getNoticeInfo")){
            getClassInfoByIdResponse response = (getClassInfoByIdResponse) result;
            if (response.isSuccess()) {
                title.setText(lists.get(count).getTitle());
                time.setText(lists.get(count).getCreateTimeText());
//                content.setText(Html.fromHtml(EscapeUnescapeUtil.unescape(response.Detail)));
                final String html = EscapeUnescapeUtil.unescape(response.Detail);
                ThreadPool.getInstance().execute(new Runnable() {
                    @Override
                    public void run() {
                        sp =  Html.fromHtml(html, new Html.ImageGetter() {
                            @Override
                            public Drawable getDrawable(String source) {
                                String s =  source.contains("http") ? source:Env.getAppContext().IP + source;
                                InputStream is = null;
                                try {
                                    is = (InputStream) new URL(s).getContent();
                                    Drawable d = Drawable.createFromStream(is,null);
                                    d.setBounds(0, 0, d.getIntrinsicWidth(),
                                            d.getIntrinsicHeight());
                                    is.close();
                                    return d;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    return null;
                                }
                            }
                        }, null);

                        mhandler.sendEmptyMessage(2);
                    }
                });


            } else {
                ToastUtil.showToast(context, response.getErrMsg());
                content.setText(response.getErrMsg());
            }
        }
    }
    private Spanned sp,sp1;
    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }


    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        int action = motionEvent.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isAutoPlay = false;
                break;
            case MotionEvent.ACTION_UP:
                isAutoPlay = true;
                break;
        }
        return false;
    }

    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    if (isAutoPlay) {
                        viewPager.setCurrentItem(++currentViewPagerItem);
                    }
                    break;
                case 2:
                    content.setText(sp);
                    break;
                case 3:
                    isFragment = true;
                    runThreadAction("XXXW");
                    runThreadAction("notice");
                    runThreadAction("honor");
                    runThreadAction("image");
                    runThreadAction("getCurrentCourse");
                    courseName.setText("正在查询课程...");
                    content.setText("正在加载学校通知...");
                    break;

                case 4:
                    TextViews.get(2).setText(sp);
                    break;
            }
        }
    };

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentViewPagerItem = position;
        if (mItems != null) {
            position %= mBottomImages.length;
            int total = mBottomImages.length;

            for (int i = 0; i < total; i++) {
                if (i == position) {
                    mBottomImages[i].setImageResource(R.drawable.indicator_select);
                } else {
                    mBottomImages[i].setImageResource(R.drawable.indicator_no_select);
                }
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    private void startAnim() {
        noice.startAnimation(animation1);
        schoolNews.startAnimation(animation1);
        teaching.startAnimation(animation2);
        classHonor.startAnimation(animation2);
    }

    private void creatCriclePoint() {
        //右下方小圆点
        mBottomImages = new ImageView[mItems.size()];
        for (int i = 0; i < mBottomImages.length; i++) {
            ImageView imageView = new ImageView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.setMargins(5, 0, 5, 0);
            imageView.setLayoutParams(params);
            //如果当前是第一个 设置为选中状态
            if (i == 0) {
                imageView.setImageResource(R.drawable.indicator_select);
            } else {
                imageView.setImageResource(R.drawable.indicator_no_select);
            }
            mBottomImages[i] = imageView;
            //添加到父容器
            mBottomLiner.addView(imageView);
        }
    }

    private void startAutoPlay() {
        if(mthread == null){
            //定时发送消息
            mthread = new Thread(){
                @Override
                public void run() {
                    super.run();
                    while (true) {
                        mhandler.sendEmptyMessage(MSG_ONE);
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            mthread.start();
        }

    }

    private List<ImageView>  addImageView(List<String> strings){
        if(!strings.isEmpty()) {
            mItems = new ArrayList<>();
            int size = strings.size() >= 3 ? 3 : strings.size();
            for(int i = 0 ; i < size ; i++) {
                ImageView view0 = new ImageView(context);
                Glide.with(context).load(Env.getAppContext().IP + strings.get(i)).asBitmap().centerCrop().placeholder(R.drawable.imageload).
                        error(R.drawable.imagefail).into(view0);
                mItems.add(view0);
            }
        }else{
            ToastUtil.showToast(context,"班级暂时没有图片");
        }
        return  mItems;

    }


    private View.OnClickListener leftListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(count == 0) {
                ToastUtil.showToast(context,"没有上一条了");
                return;
            }
            count--;
            runThreadAction("getNoticeInfo");
        }
    };
    private View.OnClickListener rightListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(count >= lists.size()-1) {
                ToastUtil.showToast(context,"没有下一条了");
                return;
            }
            count++;
            runThreadAction("getNoticeInfo");
        }
    };

    private class getCurrentCourseThread extends Thread {

        private boolean stopFlag = false;
        @Override
        public void run() {
            while (!stopFlag) {
                if(!isFragment) {
                    try {
                        Thread.sleep(60*1000*10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();

                    }
                    mhandler.sendEmptyMessage(3);
                }

            }
        }
        /**
         * 通知线程需要停止
         */
        private void stopRun() {
            stopFlag = true;
        }
    };

}
